﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace SimpComm
{
    public class HttpHelp
    {
        //   /**
        //* api方式调用使用此方法
        //* @param urlAddr 接口地址
        //* @param info  请求串
        //* @return
        //* @throws Exception
        //*/

        private static readonly int TIMEOUT = 50000; //超时5秒
        private static readonly int READ_TIMEOUT = 20000; //接收返回超时20秒

        public static string Post(string url, string data, string EnCode = "utf-8")
        {
            // 来Post数据到登陆页面
            var requestLoginToPage = (HttpWebRequest) WebRequest.Create(url);
            requestLoginToPage.ContentType = "text/html;charset=UTF-8";
            requestLoginToPage.Method = "POST";
            requestLoginToPage.Timeout = TIMEOUT;
            requestLoginToPage.ReadWriteTimeout = READ_TIMEOUT;

            try
            {
                var bytes = Encoding.ASCII.GetBytes(data);
                requestLoginToPage.ContentLength = bytes.Length;
                var streamLoginToPage = requestLoginToPage.GetRequestStream();
                streamLoginToPage.Write(bytes, 0, bytes.Length);
                streamLoginToPage.Flush();
                streamLoginToPage.Close();
                var responseLoginToPage = (HttpWebResponse) requestLoginToPage.GetResponse();
                var Data =
                    new StreamReader(responseLoginToPage.GetResponseStream(), Encoding.GetEncoding(EnCode)).
                        ReadToEnd();
                return Data;
            }
            catch (Exception ex)
            {
                throw ex;
                return null;
            }
        }

        public static string GetRemoteHtmlCode(string url, string charset)
        {
            //编码处理    
            Encoding nowCharset;
            if (charset == "" || charset == null)
            {
                nowCharset = Encoding.Default;
            }
            else
            {
                nowCharset = Encoding.GetEncoding(charset);
            }

            //处理内容    
            var html = "";
            try
            {
                var request = (HttpWebRequest) WebRequest.Create(url);
                request.Timeout = 20*1000; //连接超时
                request.Accept = "*/*";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;)";
                var response = (HttpWebResponse) request.GetResponse();
                var stream = response.GetResponseStream();
                var reader = new StreamReader(stream, nowCharset);
                html = reader.ReadToEnd();
                stream.Close();
            }
            catch (Exception)
            {
            }
            return html;
        }


        /// <summary>
        /// cookie集合 
        /// </summary>
        /// <summary>
        /// 获取页面html   encodingname:gb2312
        /// </summary>
        /// <param name="uri">访问url</param>
        /// <returns></returns>
        public static string Get(string uri)
        {
            return Get(uri, uri, "gb2312");
        }

        /// <summary>
        /// 获取页面html   encodingname:gb2312
        /// </summary>
        /// <param name="uri">访问url</param>
        /// <param name="refererUri">来源url</param>
        /// <returns></returns>
        public static string Get(string uri, string refererUri)
        {
            return Get(uri, refererUri, "gb2312");
        }

        /// <summary>
        /// 获取页面html
        /// </summary>
        /// <param name="uri">访问url</param>
        /// <param name="refererUri">来源url</param>
        /// <param name="encodingName">编码名称  例如：gb2312</param>
        /// <returns></returns>
        public static string Get(string uri, string refererUri, string encodingName)
        {
            return Get(uri, refererUri, encodingName, null);
        }

        /// <summary>
        /// 获取页面html
        /// </summary>
        /// <param name="uri">访问url</param>
        /// <param name="refererUri">来源url</param>
        /// <param name="encodingName">编码名称  例如：gb2312</param>
        /// <param name="webproxy">代理</param>
        /// <returns></returns>
        public static string Get(string uri, string refererUri, string encodingName, WebProxy webproxy)
        {
            var html = string.Empty;

            var request = (HttpWebRequest) WebRequest.Create(uri);

            request.ContentType = "text/html;charset=" + encodingName;
            request.Method = "Get";
            //request.CookieContainer = cookieContainer;

            if (null != webproxy)
            {
                request.Proxy = webproxy;
                if (null != webproxy.Credentials)
                    request.UseDefaultCredentials = true;
            }

            if (!string.IsNullOrEmpty(refererUri))
                request.Referer = HttpUtility.UrlEncode(refererUri);

            using (var response = (HttpWebResponse) request.GetResponse())
            {
                using (var streamResponse = response.GetResponseStream())
                {
                    using (
                        var streamResponseReader = new StreamReader(streamResponse, Encoding.GetEncoding(encodingName)))
                    {
                        html = streamResponseReader.ReadToEnd();
                    }
                }
            }

            return html;
        }
    }
}